/**
 * @file mongodb配置
 */

const mongoose = require('mongoose')
mongoose.Promise = global.Promise
const { readdirSync } = require('fs')
const { resolve } = require('path')

const dbConf = require('../config')[process.env.NODE_ENV || 'development'].mongodb

// const dbUri = `mongodb://${dbConf.user}:${dbConf.pass}@${dbConf.host}:${dbConf.port}/${dbConf.database}`
const dbUri = 'mongodb://localhost/myblog'

const models = resolve(__dirname, '../models')

readdirSync(models).forEach(file => {
	require(resolve(models, file))
})

exports.mongoose = mongoose

exports.connect = () => {

	if (process.env.NODE_ENV !== 'production') {
		mongoose.set('debug', true)
	}

	mongoose.connect(dbUri, {
		auth: {
			authdb: 'admin'
		}
	})
	mongoose.connection.on('connected', () => {
		console.log(`Mongoose 连接到 ${dbUri}`)
	})

	mongoose.connection.on('error', err => {
		console.log(`Mongoose 连接错误 ` + err)
	})

	mongoose.connection.on('disconnected', () => {
		console.log('Mongoose 断开连接')
	})
}